"""Initialize portfolio database tables."""
from __future__ import annotations

from typing import Any

from .logging import get_logger
from .config import get_config
from app.data.schema import initialize_database


LOGGER = get_logger(__name__)
LOG_EXTRA = {"stage": "portfolio_init"}


def get_portfolio_config() -> dict[str, Any]:
    """获取投资组合配置.
    
    Returns:
        包含以下字段的字典:
        - initial_capital: 初始投资金额
        - currency: 货币类型
        - position_limits: 仓位限制
    """
    config = get_config()
    settings = config.portfolio if hasattr(config, "portfolio") else None
    
    if not settings:
        from .config import PortfolioSettings
        settings = PortfolioSettings()
    
    return {
        "initial_capital": settings.initial_capital,
        "currency": settings.currency,
        "position_limits": {
            "max_position": settings.max_position,
            "min_position": settings.min_position,
            "max_total_positions": settings.max_total_positions,
            "max_sector_exposure": settings.max_sector_exposure
        }
    }

def update_portfolio_config(updates: dict[str, Any]) -> None:
    """更新投资组合配置.
    
    Args:
        updates: 要更新的配置项字典
    """
    from .config import get_config, save_config, PortfolioSettings
    
    # 获取当前配置
    config = get_config()
    
    # 创建新的投资组合设置
    portfolio = PortfolioSettings(
        initial_capital=updates["initial_capital"],
        currency=updates["currency"],
        max_position=updates["position_limits"]["max_position"],
        min_position=updates["position_limits"]["min_position"],
        max_total_positions=updates["position_limits"]["max_total_positions"],
        max_sector_exposure=updates["position_limits"]["max_sector_exposure"]
    )
    
    # 更新配置
    config.portfolio = portfolio
    save_config(config)



def initialize_database_schema() -> None:
    """Create database tables if they don't exist."""
    try:
        initialize_database()
    except Exception:  # noqa: BLE001
        LOGGER.exception("初始化数据库 schema 失败", extra=LOG_EXTRA)
        raise
